package cn.edu.xzit.controller;

import cn.edu.xzit.entity.Course;
import cn.edu.xzit.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
public class CourseController {

    @Autowired
    CourseService courseService;

    @GetMapping("/findAllCourse")
    public List<Course> findAllCourse() {
        return courseService.findAllCourse();
    }


    @GetMapping("/saveCourse")
    public Course saveCourse() {
        Course course = new Course();
        course.setCourseNo("0801001");
        course.setCourseName("Java Web应用开发");
        course.setTeacherNo("J00301");
        course.setTeacherName("王小二");
        course.setCredit("4");
        course.setClassHour("64");
        course.setCoursePlan("第二学期");
        courseService.saveCourse(course);
        return course;
    }

    @GetMapping("/getCourseById/{id}")
    public Course getCourseById(@PathVariable Integer id) {
        return courseService.getById(id);
    }

    @GetMapping("/getCourseByCourseNo/{courseNo}")
    public List<Course> findCourseByCourseNo(@PathVariable String courseNo) {
        return courseService.findCourseByCourseNo(courseNo);
    }

    @GetMapping("/deleteCourseById/{id}")
    public String deleteCourseById(@PathVariable Integer id) {
        courseService.deleteById(id);
        return "删除课程成功啦！";
    }

    @GetMapping("/updateCourse")
    public String updateCourse(@RequestBody Course course) {
//        Course course = new Course();
//        course.setId(1);
//        course.setCourseNo("0801001");
//        course.setCourseName("Java Web应用开发1");
//        course.setTeacherNo("J00301");
//        course.setTeacherName("王小五");
//        course.setCredit("4");
//        course.setClassHour("64");
//        course.setCoursePlan("第一学期");
        courseService.updateCourse(course);
        return "修改课程成功啦！";
    }


    @PostMapping("/findAll")
    public Page<Course> findAll(@RequestParam String current, @RequestParam String pageNum) {
        //增加传入实参的判断
        current = Objects.equals(current, "") ? "0" : current;
        pageNum = Objects.equals(pageNum, "") ? "5" : pageNum;
        PageRequest pageable = PageRequest.of(Integer.parseInt(current), Integer.parseInt(pageNum));

        Page<Course> page = courseService.findAll(pageable);
        System.out.println("总页数：" + page.getTotalPages());
        System.out.println("总的记录数：" + page.getTotalElements());
        System.out.println("查询结果：" + page.getContent());
        System.out.println("当前页数：" + page.getNumber() + 1);
        System.out.println("当前记录数：" + page.getNumberOfElements());
        System.out.println("每一页记录数：" + page.getSize());
        return page;
    }

}
